package com.drawing.client;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2023-10-10
 */
public class QiNiuYunClient {

    private static final Logger logger = LoggerFactory.getLogger(QiNiuYunClient.class);

    private static final String ACCESS_KEY = "Hax-dUavNagjJcIywSfNT85tC6ouafmOpxQqqwWh";

    private static final String SECRET_KEY = "QWssNcHckszFJQh624nNYIKfMCtHb-YcwbD03DOc";

    private static final String BUCKET_NAME = "image99999";

    private static final Auth AUTH = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static final Configuration CFG = new Configuration(Zone.zone0());

    private static final UploadManager UPLOAD_MANAGER = new UploadManager(CFG);

    private static final String QINIU_IMAGE_DOMAIN = "http://ahxiqi.com";


    public static String defaultUpToken() {
        return AUTH.uploadToken(BUCKET_NAME);
    }

    public static String queryImage(String url) {
        long expireInSeconds = 3600 * 24 * 7;
        return AUTH.privateDownloadUrl(url, expireInSeconds);
    }

    public static String saveImageToQNY(MultipartFile file) throws IOException {
        try {
            int dotPos = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            if (dotPos < 0) {
                logger.error("文件后缀不合法（没有后缀）");
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!isFileAllowed(fileExt)) {
                logger.error("文件后缀不合法");
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = UPLOAD_MANAGER.put(file.getBytes(), fileName, defaultUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                DefaultPutRet ret = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
                return QINIU_IMAGE_DOMAIN + "/" + ret.key;
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

    public static final String[] IMAGE_FILE_EXTD = new String[] {"png", "bmp", "jpg", "jpeg", "pdf", "word"};

    public static boolean isFileAllowed(String suffix) {
        return Arrays.asList(IMAGE_FILE_EXTD).contains(suffix);
    }
}
